#Alexander F. Gazmararian
#afg2@princeton.edu

# Load packages
library(tidyverse)
library(modelsummary)
library(lmtest)
library(sandwich)
library(margins)

# Load aesthetics
source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/fix_txt.r")

# Load civicpulse data
cp <- readRDS("data/CivicPulse_Public.rds")

# Load national data
g <- readRDS("data/NatQual_Winter22.rds")

# Specify baseline models
f.nat <- y ~ age + Female + Black + Hispanic +  PartySummary + CollegeDegree + employfull + Rural_bin + Investment + income5 + trust_index

## NOTE: the following variables are only in the restricted access data (see README.txt): biden2020 + Census_area_college + log(Census_area_population) + Census_area_urban
f.cp <- y ~ Age_cat + Woman + College + Minority_bin + PartySummary + Gov_type + biden2020 + Sample + Census_area_college + log(Census_area_population) + Census_area_urban
f.cp.slim <- y ~ Age_cat + Woman + College + Minority_bin  + Gov_type +  Sample

# Specify coefficient names
source("code/fun/coefnames4tables.r")
coefnames <- c(
  "law_treat"="Law Treatment",
  "lawtreat"="Law Treatment",
  "ClimateImpact_triIncrease"="Climate Policy Increase",
  "ClimateImpact_triNo change"="Climate Policy No Change",
  "law_treat:ClimateImpact_triIncrease"="Law Treatment x Climate Policy Increase",
  "law_treat:ClimateImpact_triNo change"="Law Treatment x Climate Policy No Change",
  "lawtreat:ClimateImpact_triIncrease"="Law Treatment x Climate Policy Increase",
  "lawtreat:ClimateImpact_triNo change"="Law Treatment x Climate Policy No Change",
  "clawtreat:lawtreat"="Clawback Treatment x Law Treatment",
  "clawtreat:transptreat"="Clawback Treatment x Transparency Treatment",
  "lawtreat:transptreat"="Law Treatment x Transparency Treatment",
  "clawtreat:ClimateImpact_triIncrease"="Clawback Treatment x Climate Policy Increase",
  "clawtreat:ClimateImpact_triNo change"="Clawback Treatment x Climate Policy No Change",
  "transptreat:ClimateImpact_triIncrease"="Transparency Treatment x Climate Policy Increase",
  "transptreat:ClimateImpact_triNo change"="Transparency Treatment x Climate Policy No Change",
  "clawtreat:lawtreat:transptreat"="Clawback x Law x Transparency",
  "clawtreat:lawtreat:ClimateImpact_triIncrease" = "Clawback x Law x Climate Policy Increase",
  "clawtreat:lawtreat:ClimateImpact_triNo change" = "Clawback x Law x Climate Policy No Change",
  "clawtreat:transptreat:ClimateImpact_triIncrease" = "Clawback x Transparency x Climate Policy Increase",
  "clawtreat:transptreat:ClimateImpact_triNo change" = "Clawback x Transparency x Climate Policy No Change",
  "lawtreat:transptreat:ClimateImpact_triIncrease" = "Law x Transparency x Climate Policy Increase",
  "lawtreat:transptreat:ClimateImpact_triNo change" = "Law x Transparency x Climate Policy No Change",
  "clawtreat:lawtreat:transptreat:ClimateImpact_triIncrease" =  "Clawback x Law x Transparency x Climate Policy Increase",
  "clawtreat:lawtreat:transptreat:ClimateImpact_triNo change" = "Clawback x Law x Transparency x Climate Policy No Change",
  coefnames
)

# Create Figure 5.4----

# Local policymaker sample

##NOTE: this equation uses variables from the RAD file
m.climate <- lm(update(f.cp, Transition_scale ~ clawtreat * lawtreat * transptreat * ClimateImpact_tri + .), cp)
# Extract average marginal effects
law.climate <- margins_summary(m.climate, variables = "lawtreat", at=list(ClimateImpact_tri=c("Decrease", "No change", "Increase")), vcov = vcovHC(m.climate, type = "HC2"))
law.climate <- data.frame(law.climate)
law.climate$model <- "Climate Policy Effect on Local Economy"

# National sample
m.climate.nat <- lm(update(f.nat, Promise_scale ~ law_treat * ClimateImpact_tri + .), g)
# Extract average marginal effects
nat.climate <- margins_summary(m.climate.nat, variables = "law_treat", at=list(ClimateImpact_tri=c("Decrease", "No change", "Increase")), vcov = vcovHC(m.climate.nat, type = "HC2"))
nat.climate <- data.frame(nat.climate)
nat.climate$model <- "Climate Policy Effect on Local Economy"

#bind heterogeneous effects data frames together
law.cate <- lapply(list(law.climate), function(x) {
  names(x)[2] <- "condition"
  return(x)
})
law.cate <- do.call("rbind", law.cate)
law.cate$lower90 <- with(law.cate, AME + SE * qnorm(0.05))
law.cate$upper90 <- with(law.cate, AME + SE * qnorm(0.95))

#bind heterogeneous effects data frames together
nat.cate <- lapply(list(nat.climate), function(x) {
  names(x)[2] <- "condition"
  return(x)
})
nat.cate <- do.call("rbind", nat.cate)
nat.cate$lower90 <- with(nat.cate, AME + SE * qnorm(0.05))
nat.cate$upper90 <- with(nat.cate, AME + SE * qnorm(0.95))

#create names for samples
nat.cate$sample <- "National"
law.cate$sample <- "Local policymaker"

#create common data frame
cate.df <- rbind(nat.cate, law.cate)

#create plot
promise.plot <-
  cate.df %>%
  ggplot(aes(x=condition,y=AME,color=sample,shape=sample)) +
  geom_hline(yintercept = 0, lty = "dashed", color = "grey") +
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, position = position_dodge(.5)) +
  geom_errorbar(aes(ymin = lower90, ymax = upper90), width = 0, size = 1.5, position = position_dodge(.5)) +
  geom_point(size = 4, position = position_dodge(.5)) +
  scale_x_discrete(labels = scales::label_wrap(15)) +
  scale_y_continuous(breaks = seq(-.75, .75, .25), limits=c(-.8,.8),labels = scales::number_format(accuracy = 0.01), expand = c(0,0)) +
  labs(x = "Moderator: Climate Policy Effect on Local Economy", y = "Estimate",
       caption = "Notes: Thin and thick bars denote 95 and 90 percent confidence intervals.",
       color = "", shape = "") +
  scale_color_grey() +
  book_theme +
  theme(legend.position="bottom", legend.box.margin = margin(t=-10))
promise.plot
savefig(promise.plot, "5.4_figure_promise", height = 2.5, filepath = "figures/")

# Create SI Table----
file <- "tables/ch5/ols_promiselaw.txt"
modelsummary(
  list(m.climate, m.climate.nat),
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs","adj.r.squared"),
  output = "latex",
  vcov = "HC2",
  escape = FALSE
) %>%
  cat(., file = file)
fix_txt(file)
